import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/theme/base_form_theme.dart';

/// radio 控件
class BaseFormRadio extends StatefulWidget {

  final List<BaseKeyValueModel> radioList;

  final dynamic selectedKey;

  final Function(BaseKeyValueModel) callBack;

  const BaseFormRadio({Key key, @required this.radioList, @required this.selectedKey, this.callBack}): assert(radioList != null), super(key: key);

  @override
  _BaseFormRadioState createState() => _BaseFormRadioState();

}

class _BaseFormRadioState extends State<BaseFormRadio> {

  dynamic _selectedKey;

  @override
  void initState() {
    _selectedKey = widget.selectedKey;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.radioList.length == 0) return SizedBox();
    return Container(
      height: 48,
      child: ListView.separated(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) => _buildItemRadio(widget.radioList[index]),
        separatorBuilder: (_, __) => SizedBox(width: 8),
        itemCount: widget.radioList.length,
      ),
    );
  }

  /// 构建 radio
  Widget _buildItemRadio( BaseKeyValueModel item ) {
    Color primaryColor = Theme.of(context).primaryColor == Colors.white ? Theme.of(context).textTheme.bodyText2.color : Theme.of(context).primaryColor;
    bool isSelected = item.key == _selectedKey;
    Color borderColor = isSelected ? primaryColor : BaseFormTheme.borderColor;
    Color textColor = isSelected ? Colors.white : primaryColor;
    Color backGroundColor = isSelected ? primaryColor : Colors.white;
    return UnconstrainedBox(
      child: InkWell(
        borderRadius: BorderRadius.circular(2),
        onTap: () => _onSelect( item ),
        child: ConstrainedBox(
          constraints: BoxConstraints(minWidth: 40),
          child: Container(
            height: 24,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 8),
            decoration: BoxDecoration(color: backGroundColor, border: Border.all(width: 1, color: borderColor), borderRadius: BorderRadius.circular(2)),
            child: Text(item.value, softWrap: false, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 13, color: textColor)),
          ),
        ),
      ),
    );
  }

  void _onSelect( BaseKeyValueModel item ) {
    if (_selectedKey != item.key) {
      setState(() {
        _selectedKey = item.key;
        if (widget.callBack != null) widget.callBack(item);
      });
    }
  }

}
